package activity

import android.Manifest
import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.Button
import android.widget.ImageView
import com.hontech.kdxclient.R
import event.*
import manager.*
import mvc.model.view.MenuView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import popup.*
import task.RefreshSellTask
import task.TakeButtonCtrlTask
import view.CustomMediaPlayer
import view.MenuItemView

class MainActivity : AppCompatActivity() {
    companion object {
        const val PERMISSION_REQUEST = 0x01
        const val QUIT_ACTION = "quit.action"
        var isShow = true
    }

    private val mTopPlayer: CustomMediaPlayer by lazy { findViewById<CustomMediaPlayer>(R.id.id_main_player_top) }
    private val mBottomPlayer: CustomMediaPlayer by lazy { findViewById<CustomMediaPlayer>(R.id.id_main_player_bottom) }
    private val mRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.id_main_recycler_view) }
    private val mImageViewBounce: ImageView by lazy { findViewById<ImageView>(R.id.id_main_image_point) }
    private val mButtonDebug: Button by lazy { findViewById<Button>(R.id.id_main_button_debug) }
    private val mButtonTakeGoods: Button by lazy { findViewById<Button>(R.id.id_main_button_take_goods) }
    private val mTakeButtonCtrl: TakeButtonCtrlTask by lazy { TakeButtonCtrlTask(mButtonTakeGoods) }

    private lateinit var mRecyclerViewAdapter: RecyclerViewAdapter
    private lateinit var mAutoScrollAnim: RecyclerViewAutoScrollManager
    private lateinit var mBounceAnim: Animation

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestPermission()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            EventBus.getDefault().post(SellChangedEvent(RefreshSellTask.SellStatus))
        }
    }

    override fun onResume() {
        super.onResume()
        isShow = true
        mTopPlayer.onResume()
        mBottomPlayer.onResume()
    }

    override fun onPause() {
        super.onPause()
        isShow = false
        mTopPlayer.onPause()
        mBottomPlayer.onPause()
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val flag = intent.getBooleanExtra(MainActivity.QUIT_ACTION, false)
        if (flag) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun onClickDebug(view: View): Boolean {
        UserLoginWindow.Instance.show(mRecyclerView)
        return true
    }

    private fun requestPermission() {
        val ret = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                PERMISSION_REQUEST
            )
        } else {
            onInit()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PERMISSION_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            onInit()
        }
    }

    private fun onInit() {
        mRecyclerViewAdapter = RecyclerViewAdapter(::onItemClick)
        mRecyclerView.adapter = mRecyclerViewAdapter
        mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        mRecyclerView.addItemDecoration(RecyclerViewItemDecoration())
        mAutoScrollAnim = RecyclerViewAutoScrollManager(mRecyclerView)
        mTopPlayer.onCompletion = ::onTopComplete
        mBottomPlayer.onCompletion = ::onBottomComplete

        mButtonDebug.setOnLongClickListener(::onClickDebug)

        mBounceAnim = TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_SELF,
            0f,
            TranslateAnimation.RELATIVE_TO_SELF,
            0f,
            TranslateAnimation.RELATIVE_TO_SELF,
            0f,
            TranslateAnimation.RELATIVE_TO_SELF,
            0.2f
        )
        mBounceAnim.duration = 500
        mBounceAnim.repeatCount = Animation.INFINITE
        mBounceAnim.repeatMode = Animation.REVERSE
        mImageViewBounce.startAnimation(mBounceAnim)
        isShow = true
        TaskManager.UiHandler.postDelayed({
            AppManager.initApp()
        }, 2000)
        mTakeButtonCtrl.hide()
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onPaySuccessEvent(env: PaySuccessEvent) {
        mTakeButtonCtrl.hide()
        PayWindow.Instance.dismiss()
        DeliveryWindow.Instance.show(mRecyclerView)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliverCompleteEvent(env: DeliverCompleteEvent) {
        if (StatusManager.status.raster != 0x00) { // 光栅被遮挡
            mTakeButtonCtrl.show()
            mTakeButtonCtrl.hideWithDuration()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onTakeButtonClickEvent(env: TakeButtonClickEvent) {
        TakeGoodsWindow.Instance.show(mRecyclerView)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onInventoryChangedEvent(env: InventoryChangedEvent) // 库存发生变化
    {
        mAutoScrollAnim.stop()
        mRecyclerViewAdapter.notifyDataSetChanged()
        mAutoScrollAnim.start()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) // 广告发生变化
    fun onAdvChangedEvent(env: AdvChangedEvent) {
        val top = AdvertisingManager.findTopNextMedia()
        val bottom = AdvertisingManager.findBottomNextMedia()
        mTopPlayer.setUp(top)
        mBottomPlayer.setUp(bottom)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onUserLoginChangedEvent(env: LoginChangedEvent) {
        when (env.type) {
            LoginChangedEvent.INFO -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, InfoActivity::class.java)
                startActivity(i)
            }

            LoginChangedEvent.SCAN -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, ScanActivity::class.java)
                startActivity(i)
            }

            LoginChangedEvent.SET -> {
                UserLoginWindow.Instance.dismiss()
                val i = Intent(this, SettingActivity::class.java)
                startActivity(i)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusChangedEvent(env: StatusChangedEvent) {
        if (AppManager.isBusy) {
            return
        }

        if (env.status.trouble) {
            FaultWindow.Instance.showWithTitle(env.status.errorMessage, mRecyclerView)
        } else {
            FaultWindow.Instance.dismiss()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onSellChangedEvent(env: SellChangedEvent) {
        if (AppManager.isBusy) {
            return
        }
        if (env.status == SellChangedEvent.START) {
            SellPopupWindow.Instance.dismiss()
        } else if (env.status == SellChangedEvent.STOP) {
            SellPopupWindow.Instance.show(mRecyclerView)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onMqttChangedEvnet(env: MqttChangedEvent) {
        if (env.link) {
            NetworkFaultWindow.Instance.dismiss()
        } else {
            NetworkFaultWindow.Instance.show(mBottomPlayer)
        }
    }

    private fun onTopComplete() {
        val top = AdvertisingManager.findTopNextMedia()
        mTopPlayer.setUp(top)
    }

    private fun onBottomComplete() {
        val bottom = AdvertisingManager.findBottomNextMedia()
        mBottomPlayer.setUp(bottom)
    }

    private fun onItemClick(position: Int) {
        WaresManager.SelectIndex = position
        PayWindow.Instance.show(mRecyclerView)
    }

    private class RecyclerViewAutoScrollManager(val recyclerView: RecyclerView) : ValueAnimator.AnimatorUpdateListener {
        private val animator = ValueAnimator.ofInt(0, 1)

        init {
            animator.addUpdateListener(this)
            animator.repeatCount = ValueAnimator.INFINITE
            animator.repeatMode = ValueAnimator.RESTART
            animator.duration = 300
        }

        override fun onAnimationUpdate(animation: ValueAnimator) {
            recyclerView.scrollBy(1, 0)
        }

        fun start() {
            animator.start()
        }

        fun stop() {
            animator.cancel()
            recyclerView.scrollToPosition(0)
        }
    }

    private class RecyclerViewAdapter(val onItemClick: (Int) -> Unit) : RecyclerView.Adapter<MenuView>() {
        override fun onBindViewHolder(holder: MenuView, position: Int) {
            val p = position % WaresManager.size
            val info = WaresManager[p]
            holder.menuItem.setWaresInfo(info, onItemClick, p)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuView {
            return MenuView(MenuItemView(parent.context))
        }

        override fun getItemCount(): Int {
            val number = WaresManager.size
            if (number <= 0) {
                return 0
            }
            return Int.MAX_VALUE
        }
    }

    private class RecyclerViewItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
            super.getItemOffsets(outRect, itemPosition, parent)
            outRect.left = 5
            outRect.top = 5
        }
    }
}
